package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.NoArgsConstructor;
import feces.model.Product;
import feces.model.Productshoping;
import feces.model.StorehouseProduct;
import feces.utility.Utility;
@WebServlet(name="pro", urlPatterns={"/api/pro"})
@NoArgsConstructor
public class ShoppingProduct extends RESTfulServlet{
	/**
	 * 响应GET请求
	 * 获取商品
	 * 
	 * @return 查询结果，可能为空
	 */
	@Override
	protected Response<Productshoping> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		String parameter = request.getParameter("id");
		if (parameter == null) {
			return invalid(null);
		}
		Integer id = Utility.toInteger(parameter);
		if (id == null) {
			return invalid(null);
		}
		Product product = find(Product.class, id);
			List<StorehouseProduct> shpProduct;

			int sum=0;
			shpProduct= executeQuery(
			"SELECT DISTINCT e FROM StorehouseProduct e WHERE e.productId = ?1", 
			StorehouseProduct.class,product.getId());
			for(int k=0;k<shpProduct.size();k++)
			{
				StorehouseProduct shp = shpProduct.get(k);
				sum=sum+shp.getQuantity();
			}
			Productshoping prosh=new Productshoping();
			prosh.setProduct(product);
			prosh.setSum(sum);
			
		if (product != null) {
			return succeed(prosh);
		}
		return failed(null);
	}
	
}
